import 'dart:async';

import 'package:flutter/material.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_uikit/lib_uikit.dart';
import 'package:lib_uikit/resource/resources.dart';
import 'package:lib_uikit/utils/gt_text_style.dart';
import 'package:lib_uikit/widgets/gt_toast.dart';
import 'package:lib_uikit/widgets/text/gt_text.dart';

class GTToastV3 {
  static final GTToastV3 _instance = GTToastV3._internal();

  factory GTToastV3() => _instance;

  GTToastV3._internal();

  void showToast(BuildContext? context, ToastLevel level, String? message) {
    if (message != null && message.isNotEmpty) {
      _CustomToastV3().showToast(context, level, message,
          duration: message.length > 30
              ? const Duration(milliseconds: 3500)
              : const Duration(seconds: 2));
    }
  }
}

class _CustomToastV3 {
  String? _lastMessage;
  DateTime? _lastToastTime;
  OverlayEntry? _lastOverlayEntry;
  static final _CustomToastV3 _instance = _CustomToastV3._internal();

  factory _CustomToastV3() => _instance;

  _CustomToastV3._internal();

  void showToast(BuildContext? context, ToastLevel level, String message,
      {Duration duration = const Duration(seconds: 2)}) {
    // 获取 OverlayState
    OverlayState? overlayState;
    if (context != null) {
      overlayState = Overlay.of(context);
    } else {
      overlayState = GTNavigatorProvider.navigatorKey.currentState?.overlay;
    }
    // OverlayState 为 null 时，不弹 toast
    if (overlayState == null) {
      return;
    }

    final currentTime = DateTime.now();
    if (message == _lastMessage) {
      if (message.length <= 30) {
        if (_lastToastTime != null &&
            currentTime.difference(_lastToastTime!) <
                const Duration(seconds: 2)) {
          return;
        }
      } else {
        if (_lastToastTime != null &&
            currentTime.difference(_lastToastTime!) <
                const Duration(milliseconds: 3500)) {
          return;
        }
      }
    }
    _lastOverlayEntry?.remove();
    final overlayEntry = OverlayEntry(
      builder: (BuildContext context) {
        return _buildToastWidget(context, level, message);
      },
    );
    overlayState.insert(overlayEntry);
    _lastOverlayEntry = overlayEntry;
    _lastMessage = message;
    _lastToastTime = currentTime;
    Timer(duration, () {
      if (_lastOverlayEntry != null) {
        _lastOverlayEntry!.remove();
        _lastOverlayEntry = null;
      }
    });
  }

  Widget _buildToastWidget(
      BuildContext context, ToastLevel level, String message) {
    String? iconAsset;
    switch (level) {
      case ToastLevel.error:
        iconAsset = Images.icToastError;
        break;
      case ToastLevel.success:
        iconAsset = Images.icToastSuccess;
        break;
      case ToastLevel.warning:
        iconAsset = Images.icToastWarning;
        break;
      default:
        iconAsset = null;
        break;
    }
    final icon = iconAsset != null
        ? Image.asset(
            iconAsset,
            width: 16,
            height: 16,
          )
        : null;
    return Center(
      child: Material(
        color: Colors.transparent,
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          constraints: const BoxConstraints(
            maxWidth: 279,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(6),
            color: GTColorsV3.cmpt6.color,
          ),
          child: Row(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              if (icon != null) icon,
              if (icon != null) const SizedBox(width: 8),
              Flexible(
                child: GTText(
                  message,
                  removeTopBottomPadding: true,
                  style: gtTextStyleW500(
                    fontSize: 12,
                    color: GTColorsV3.text6.color,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
